package com.zmx.piglearn

import android.content.Context
import android.content.ContextWrapper
import android.graphics.*
import android.media.MediaRecorder
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.*
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import java.io.IOException
import java.util.*

class MainActivity : AppCompatActivity() {

    private val TAG = "###"
    private lateinit var context: Context
    private lateinit var btnControl: Button
    private lateinit var recorder: MediaRecorder
    private var isRecording = false
    private var filePath: File? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        context = this
        filePath = ContextWrapper(context).getExternalFilesDir(android.os.Environment.DIRECTORY_DOCUMENTS)
        bindViews()
    }

    private fun bindViews() {
        btnControl = findViewById(R.id.btn_control)
        btnControl.setOnClickListener { onClick(it) }
    }

    private fun onClick(view: View) {
        when (view.id) {
            R.id.btn_control -> {
                isRecording = !isRecording
                if (isRecording) {
                    startRecord()
                    btnControl.text = "停止录制"
                } else {
                    stopRecord()
                    btnControl.text = "开始录制"
                }
            }
        }
    }

    private fun startRecord() {
        recorder = MediaRecorder()
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC)
        recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT)
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT)

        val filename = Date().toString() + ".mp3"
        Log.i(TAG, filename)
        val file = File(filePath, filename)
        recorder.setOutputFile(file)

        try {
            recorder.prepare()
            recorder.start()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun stopRecord() {
        recorder.stop()
        recorder.release()
        Toast.makeText(context, "File ready at " + filePath.toString(), Toast.LENGTH_LONG).show()
    }
}